#ifndef __MY__SERVICE__
#define __MY__SERVICE__
#include"httplib.h"
#include"util.hpp"
#include"config.hpp"
#include<time.h>
extern cloud::DataManager *_data;
namespace cloud{
	class Service{
		//搭建服务器，进行业务处理
		//有三个请求upload、listshow、download
		private:
		int _server_port;
		std::string _server_ip;
		std::string _download_prefix;
		httplib::Server _server;
		static void Upload(const httplib::Request &req,httplib::Response &rsp){
			if(req.has_file("file")==false)
				return ;
			//获取req中的文件，再创建一个文件放入储存路径
			const auto & file=req.get_file_value("file");
			//file.filename--文件名  file.content--文件内容
			std::string back_dir=Config::GetInstance()->GetBackDir();
			//怕传过来的文件名含有多个‘/’怕坏文件名统一性
			std::string realpath=back_dir+FileUtil(file.filename).FileName();
			FileUtil fu(realpath);
			fu.SetContent(file.content);//将数据写入文件中
			BackInfo bi;
			bi.NewBackInfo(realpath);
			_data->Insert(bi);	
			return ;
		}
		static std::string TimeToStr(time_t time){
			return std::ctime(&time);	
			
		}
		static void ListShow(const httplib::Request &req,httplib::Response &rsp){
			//先获取所有文件数据，然后遍历依次返回数据
			std::vector<BackInfo > arry;
			_data->GetAll(&arry);
			//接下来组织html页面信息
			std::stringstream ss;
			ss<<"<html><head><title>Download</title></head>";
			ss<<"<body><h1><Download></h1><table>";
			for(auto a:arry){
			ss<<"<tr>";	
			std::string filename =FileUtil(a._real_path).FileName();
			ss<<"<td><a href='"<<a._url<<"'>"<<filename<<"</a></td>";
			ss<<"td align='right'>"<<TimeToStr(a._mtime)<<"</td>";
			ss<<"td align='right'>"<<a._fsize/1024<<"k </td>";
			ss<<"/tr";
			}
			ss<<"</table></body></html>";
			rsp.body=ss.str();
			rsp.set_header("Content-Type","text/html");
			rsp.status=200;
			return ;
		}
		
		static void Download(const httplib::Request &req,httplib::Response &rsp){}
		
		public:
		Service(){
			Config *config=Config::GetInstance();
			_download_prefix=config->GetDownloadPrefix();	
			_server_port=config->GetServerPort();	
			_server_ip=config->GetServerIp();
			//编译器会自己调用Server的默认构造函数		
		}
		void RunModule(){
			_server.Post("/upload",Upload);
			_server.Get("/showlist",ListShow);
			_server.Get("/",ListShow);
			std::string download_url=_download_prefix+"(.*)";
			_server.Get(download_url,Download);
			_server.listen(_server_ip.c_str(),_server_port);
		}
};
	
	
	
	
	
	
	
	
			

}
#endif
